package com.spring.security.app.config;

import com.spring.security.core.authorize.AuthorizeConfigManager;
import com.spring.security.core.authtication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.spring.security.core.config.FormAuthenticationConfig;
import com.spring.security.core.properties.SecurityConstants;
import com.spring.security.core.validate.config.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * oauth资源服务器配置
 *
 * @author seabed_moon
 */
@Configuration
@EnableResourceServer
public class SpringResourceServerConfig extends ResourceServerConfigurerAdapter {


    private final SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    private final FormAuthenticationConfig formAuthenticationConfig;

    private final ValidateCodeSecurityConfig validateCodeSecurityConfig;

    private final AuthorizeConfigManager authorizeConfigManager;

    private final LogoutSuccessHandler logoutSuccessHandler;

    public SpringResourceServerConfig(SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig, FormAuthenticationConfig formAuthenticationConfig, ValidateCodeSecurityConfig validateCodeSecurityConfig, AuthorizeConfigManager authorizeConfigManager, LogoutSuccessHandler logoutSuccessHandler) {
        this.smsCodeAuthenticationSecurityConfig = smsCodeAuthenticationSecurityConfig;
        this.formAuthenticationConfig = formAuthenticationConfig;
        this.validateCodeSecurityConfig = validateCodeSecurityConfig;
        this.authorizeConfigManager = authorizeConfigManager;
        this.logoutSuccessHandler = logoutSuccessHandler;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        formAuthenticationConfig.configure(http);

        http.apply(validateCodeSecurityConfig)
            .and()
              .apply(smsCodeAuthenticationSecurityConfig)
            .and()
              .logout()
                .logoutUrl(SecurityConstants.DEFAULT_SIGN_OUT_OAUTH_URL_FORM)
                .logoutSuccessHandler(logoutSuccessHandler)
                .clearAuthentication(true)
                .deleteCookies(SecurityConstants.DEFAULT_PARAMETER_NAME_SESSIONS)
            .and()
            .csrf().disable();

        authorizeConfigManager.config(http.authorizeRequests());
    }

}
